const express = require("express");
const db = require("../libs/DBHelper");
const moment = require("moment");

//fileSystem 
const fs = require("fs");

const AccountRoter = express.Router();


//登录 
AccountRoter.post("/login", async (request, response) => {
    let sql = 'SELECT * FROM userinfo where u_phone=? and u_status=1';
    let prams = [
        request.body.name,

    ]
    //返回的是一个数组
    try {
        let result = await db.exec(sql, prams);
        // console.log(result);
        // delete result[0].u_pwd;
        let isLogin = result && result.length >= 1;
        response.json({
            msg: isLogin ? "登录成功" : "登录失败",
            code: isLogin ? 200 : -200,
            data: isLogin ? result[0] : {}
        });
    } catch (error) {
        response.json({
            msg: "登录失败",
            code: -200,
            error
        });
    }
})


AccountRoter.post("/register", async (request, response) => {
    //1.准备sql语句
    let sql_reg = "INSERT INTO `userinfo` (`u_phone` , `u_pwd`)VALUES(? , ?)";
    //2.准备参数
    let params_reg = [
        request.body.name,
        request.body.pwd,
        /*  request.body.sex,
         moment().format("YYYY-MM-DD HH:mm:ss") */
    ]
    //3.执行sql语句
    try {
        let result = await db.exec(sql_reg, params_reg);

        let isReg = result && result.affectedRows;

        response.json({
            msg: isReg ? "注册成功!" : "注册失败",
            code: isReg ? 200 : -200
        });

    } catch (error) {
        response.json({
            msg: "注册失败",
            code: -200,
            error
        });
    }
    //4.判断结果
})

//get请求
AccountRoter.get("/produList", function (request, response) {
    var strData = fs.readFileSync("./data/products.json").toString();
    response.json(JSON.parse(strData || '[]'));
})

//根据id,查询产品
//动态路由传参
// xxx/:id   --> params.id
// get       --> query
// post      --> body
AccountRoter.get("/search/:id", function (request, response) {
    console.log(request.params.id);
    var strData = fs.readFileSync("./data/products.json").toString();
    var produData = JSON.parse(strData);
    var currentData = produData.find(item => item.pId == request.params.id);
    response.json(currentData)
})

//加入购物车
AccountRoter.post("/addCart", async function (request, response) {
    //1.查询是否已经购买
    let query = "SELECT * FROM `cart` WHERE `u_id`=? AND `c_name`=? AND `c_status`='1';"
    let query_params = [
        request.body.u_Id,
        request.body.pName
    ]
    let result = await db.exec(query, query_params);
    let isAdd = result && result.length >= 1;
    console.log(isAdd);
    if (isAdd) {
        //如果已经购买,修改数量
        let update_sql = "UPDATE `cart` SET `c_number` =c_number+? ,`c_total`=`c_price`*`c_number` WHERE  `u_id`=? AND `c_name`=? AND `c_status`='1';";
        let upadate_params = [
            request.body.number,
            request.body.u_Id,
            request.body.pName

        ]

        let update_result = await db.exec(update_sql, upadate_params);
        let update_status = update_result.affectedRows >= 1;

        response.json({
            msg: update_status ? "加入购物车成功!U" : "加入购物车失败!",
            code: update_status ? 200 : -200
        })

    } else {
        //如果未购买,插入
        let insert_sql = "INSERT INTO `cart` (`c_name`,`c_price`,`c_number`,`c_pic`,`c_total`,`u_id`,`c_datetime`)"
        insert_sql += " VALUES(?,?,?,?,?,?,?) ;"

        // number: "1"
        // pId: "10002"
        // pName: "小米电视EA66"
        // pPrice: 2689
        // pic: "./images/1_2.jpeg"
        // u_Id: 2

        let insert_params = [
            request.body.pName,
            request.body.pPrice,
            request.body.number,
            request.body.pic,
            request.body.pPrice * request.body.number,
            request.body.u_Id,
            moment().format("YYYY-MM-DD HH:mm:ss")
        ]

        let insert_result = await db.exec(insert_sql, insert_params);
        let insert_status = insert_result && insert_result.affectedRows;

        response.json({
            msg: insert_status ? "加入购物车成功!" : "加入购物车失败!",
            code: insert_status ? 200 : -200
        });
    }
})


//post 请求,根据u_Id 查询 购物车
AccountRoter.post("/getCartById", async (request, response) => {
    let sql = " SELECT * FROM cart WHERE `u_id`=? AND `c_status`=1;";
    let params = [
        request.body.u_Id
    ]
    var result = await db.exec(sql, params);

    response.json({
        msg: "查询成功",
        code: 200,
        data: result
    })
})

//软删除 
AccountRoter.post("/deleteCart", async (request, response) => {
    let sql = " UPDATE cart SET `c_status`=0 WHERE `c_id`=?";
    let params = [
        request.body.c_id
    ]
    var result = await db.exec(sql, params);

    let isDelete = result && result.affectedRows >= 1

    response.json({
        msg: isDelete ? "删除成功" : "删除失败",
        code: isDelete ? 200 : -200
    })
})

AccountRoter.post("/updateCart", async (request, response) => {

    //如果已经购买,修改数量
    let update_sql = "UPDATE `cart` SET `c_number` =? ,`c_total`=`c_price`*`c_number` WHERE  `c_id`=? AND `c_status`='1'"
    let update_params = [

        request.body.c_Number,
        request.body.c_id,
    ]

    let update_result = await db.exec(update_sql, update_params);
    let update_status = update_result && update_result.affectedRows >= 1;

    response.json({
        msg: update_status ? "修改商品数量成功!" : "修改商品数量失败!",
        code: update_status ? 200 : -200
    })
})




module.exports = AccountRoter;